package org.kinglone.basic.service;

import java.util.List;

import javax.annotation.Resource;

import org.kinglone.basic.dao.UserDao;
import org.kinglone.basic.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
@Transactional(readOnly=false)
public class UserServiceImp implements UserService {

	@Resource
	private UserDao userDao;
	
	@Override
	public void add(User user) {
		User u = this.loadByUsername(user.getUsername());
		if(u!=null) throw new RuntimeException("用户名已经存在");
		user.setStatus(1);
		userDao.save(user);
	}

	@Override
	public void update(User user) {
		userDao.update(user);

	}

	@Override
	public void delete(int id) {

		userDao.deleteById(id);
	}

	@Override
	public User load(int id) {
		
		return userDao.load(id);
	}

	@Override
	public User loadByUsername(String username) {
		
		return userDao.loadByUsername(username);
	}

	@Override
	public User loadByOpenid(String openid) {
		return userDao.loadByOpenId(openid);
	}

	@Override
	public User login(String username, String password) {
		User u = this.loadByUsername(username);
		if(u==null) throw new RuntimeException("用户名不存在!");
		if(!password.equals(u.getPassword())) throw new RuntimeException("用户密码不正确！");
		if(u.getStatus()==0) throw new RuntimeException("用户已经停用!");
		return u;
	}

	@Override
	public List<User> list() {
		return userDao.list();
	}

}
